<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of service_controller
 *
 * @author maylor
 */
class service_controller extends controller {
    //put your code here
     public function __construct()
    {
        parent::__construct();
    }
    
    
    public function tasks() {
        logging_run('进入操作任务进程');
        $lock_key = "tasks_lock_time";
        $bool = mredis::get($lock_key);
        if(empty($bool)) {
            mredis::setnxe($lock_key,1,20);
            $this->doArticle();
            mredis::del($lock_key);
        }else {
            logging_run('任务正在处理中');
        }
    }
    
    public function doArticle() {
        logging_run('开始任务');
        $limit = 100;
        $classes = db::select("select * from `classlist` where status=1 order by id desc limit 1000");
        $toUrl = REMOTEAPI."/dataapi/content";
        $data  = db::select("select * from `caiji` where status=0 limit $limit");
        $yuming_arr = [];
        $lcount = 0;
        foreach($data as $value) {
            $aid = $value['id'];
            if (empty($value['title'])||empty($value['content'])) {
                db::query("update `caiji` set status=2 where id='$aid'");
                logging_run("空标题或者空内容");
                continue;
            }
            if(!empty($value['yuming_id'])) {
                $classes = db::select("select * from `classlist` where yuming_id=".$value['yuming_id']." and  status=1 order by id desc limit 1000");
            }
            $res_class = $this->find_class($value['class'],$classes);
            $yuming_id = $res_class['yuming_id'];
            $class= $res_class['ename'];
            $title = $value['title'];
            //文章查重
            if(!in_array($yuming_id, $yuming_arr)) {
                $yuming_arr[] = $yuming_id;
            }
            $title = trim($title);
            $article=db::find("select * from `content_{$yuming_id}` where title='$title'");
            if($article ) {
                logging_run("采集到重复文章跳过");
                continue;
            }
            
            $filecontent = str_replace(array("<p>(点击图片看大图)</p>","显示全文"), "",$value['content']);
            //过滤原标题
            $filecontent = str_replace("原标题：", "", $filecontent);
            $filecontent = preg_replace("/20\d{2}-\d{2}-\d{2} \d{2}:\d{2}/i", "", $filecontent);
            $filecontent = str_replace("</p></p>", "</p>", $filecontent);
            $filecontent = str_replace("<p><p align=\"center\">", "<p align=\"center\">", $filecontent);
            $filecontent = preg_replace("/上一页.*?下一页/", "", $filecontent);
            //获取描述内容
            $description=strip_tags($filecontent);
            $description=trim($description);
            $description=str_replace(array(" "," "), "", $description);
            $description=mb_substr($description, 0, 150, 'utf-8');
            $description=addslashes($description);
            
             //图片处理
            $filecontent=yumi::convert_images_patch($filecontent,'',$toUrl, $yuming_id);
             // 标题自动优化
            $seo_keyword=yuminew::autoseo($title, $yuming_id);
            //同义词替换
            $filecontent=yuminew::replace_word($filecontent, $yuming_id);
            
            //关键词优化
            $seod['title']=$title;
            $seod['body']=$filecontent;
            $seod=yuminew::seoword($seod, $yuming_id);
            $title=$seod['title'];
            $filecontent=$seod['body'];
            
            //取出图片存入数据库
            if (preg_match('#src="([^"]*)"#', $filecontent, $nt)) {
                $thumb = $nt[1];
            } else {
                $thumb = '';
            }
            $addtime = time();
            //文章标记
            $flag = '';
            if ($addtime%7==0) {
                $flag = "h";   //头条
            } elseif ($addtime%11==0) {
                $flag = "c";   //推荐
            } elseif ($addtime%17==0) {
                $flag = "a";   //推荐
            } elseif ($thumb && $addtime%3==0) {
                $flag = "f";   //推荐
            }
            $title = strip_tags($title);
            $title = addslashes($title);
            $seo_keyword = addslashes($seo_keyword);
            //自动添加tag
            //存入标签
            db::query("insert into `content_{$yuming_id}`(title,flag,source,thumb,status,description,addtime,class,seo_keyword)  values ('$title','$flag','','$thumb','1','$description','$addtime','$class','$seo_keyword')");
            $id=db::insert_id();
            $this->insert_tags($seod['sw_arr'], $yuming_id, $id);
            //将文章内容存入文件
            ymcms::article_write($yuming_id, $id, $filecontent);
            db::query("update `caiji` set status=1 where id='$aid'");
            $lcount++;
        }
        //百度主动推送
        foreach($yuming_arr as $yuid) {
            yumi::baidu_push($yuid, $limit);
        }
        logging_run('完成一次任务，处理数量：'.$lcount);
    }
    
    
    //查找所属域名和分类
    protected function find_class($text,$classes) {
        $all_t = [];
        $pre_t = [];
        if(empty($text)) {
            $k =  array_rand($classes);
            return $classes[$k];
        }
        foreach($classes as $v) {
            if($v['title']==$text) {
                $all_t[] = $v;
            }elseif(strpos($v,$text)>0) {
                $pre_t[] = $v;
            }
        }
        if(!empty($all_t)) {
            $re = $all_t;
        }elseif(!empty($pre_t)) {
            $re = $pre_t;
        }else {
            $re = $classes;
        }
        $k = array_rand($re);
        return $re[$k];
    }
    
    private function insert_tags($tags, $yuming_id, $content_id){
		db::query("delete from tagindex_{$yuming_id} where aid='$content_id'");
		if(!empty($tags)){
			$time = time();
			$tagstr = implode("','", $tags);
			$res = db::select("select id,tagsname from tagslist_{$yuming_id} where tagsname in ('$tagstr') AND yuming_id='$yuming_id'");
			$oldtags = array();
			foreach ($res as $v) {
				$oldtags[] = $v['tagsname'];
			}
			foreach($tags as $key => $value){
				if(!in_array($value, $oldtags)) {
					db::query("insert into tagslist_{$yuming_id} (tagsname,addtime,yuming_id) values('$value', '$time','$yuming_id') ");
				}
			}
			db::query("insert into tagindex_{$yuming_id} (aid,tagid) select '$content_id',id from tagslist_{$yuming_id} where tagsname in ('$tagstr') AND yuming_id='$yuming_id'");
		}
	}

}
